//
//  XMLOAuthViewController.swift
//  Weibo
//
//  Created by mac on 16/5/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

let weiboAppKey = "1425344521"
let weiboRedirect_uri = "http://www.itcast.cn"
let weiboAppSecret = "1440880ee567e81e71bee4cac738cf0f"

class XMLOAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavUI()
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(weiboAppKey)&redirect_uri=\(weiboRedirect_uri)"
        let request = NSURLRequest(URL: NSURL(string: url)!)
        webView.loadRequest(request)
        
    }
    
    
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", font: 15, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", font: 15, target: self, action: "autoFillAction")
        navigationItem.title = "微博登陆"
    }
    
    //  MARK:   - 点击事件
    @objc private func cancelAction() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillAction() {
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18700913452'; document.getElementById('passwd').value = 'mn12141021xue'")
    }
    
    
//    private func requestAccessToken(code :String) {
//        
//        XMLNetWorkTools.sharedTools.requestAccessToken(code) { (response, error) -> () in
//            if error != nil {
//                print("网络请求异常")
//                return
//            }
//            
//            guard let dict = response as? [String :AnyObject] else {
//            
//                return
//            }
//            
//            let userAcount = XMLUserAcount(dict: dict)
//            self.requestUserInfo(userAcount)
//        }
//    
////        let url = "https://api.weibo.com/oauth2/access_token"
////        let params = [
////        
////            "client_id" : weiboAppKey,
////            "client_secret" : weiboAppSecret,
////            "grant_type" : "authorization_code",
////            "code" : code,
////            "redirect_uri" : weiboRedirect_uri
////        ]
////        let manager = AFHTTPSessionManager()
////        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
////        manager.POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
////            
//////            print(response)
////            guard let dict = response as? [String: AnyObject] else {
////            
////                return
////            }
////            let userAcount = XMLUserAcount(dict: dict)
////            print(userAcount)
////            self.requestUserInfo(userAcount)
////            
////            
////            }) { (_, error) -> Void in
////                print(error)
////        }
//    }
    
//    private func requestUserInfo(userAcount: XMLUserAcount) {
//        
//        XMLNetWorkTools.sharedTools.requestUserInfo(userAcount) { (response, error) -> () in
//            if error != nil {
//                print("网络下载异常")
//                return
//            }
//            guard let dict = response as? [String :AnyObject] else {
//            
//                return
//            }
//            userAcount.name = dict["name"] as? String
//            userAcount.avatar_large = dict["avatar_large"] as? String
//            print(userAcount.name,userAcount.avatar_large)
//            userAcount.saveUserAcount()
//        }
//    
////        let url = "https://api.weibo.com/2/users/show.json"
////        let params = [
////        
////            "access_token" : userAcount.access_token!,
////            "uid" : userAcount.uid
////        ]
////        let manager = AFHTTPSessionManager()
////        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
////        manager.GET(url, parameters: params, progress: nil, success: { (_, response) -> Void in
////            
////                        print(response)
////            guard let dict = response as?[String :AnyObject] else {
////            
////                return
////            }
////            
////            userAcount.name = dict["name"] as? String
////            
////            userAcount.avatar_large = dict["avatar_large"] as? String
////            print(userAcount.name)
////            
////            }) { (_, error) -> Void in
////                print(error)
////        }
//    }

}
extension XMLOAuthViewController: UIWebViewDelegate {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else {
        
            return false
        }
//        print(request.URL?.absoluteString)
        
        if !url.absoluteString.hasPrefix(weiboRedirect_uri) {
        
            return true
        }
        
        if let query = url.query where query.hasPrefix("code=") {
        
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
//            requestAccessToken(code)
            XMLUserAcountViewModel.sharedUserAcountViewModel.requestAccessToken(code, complete: { (isSuccess) -> () in
                if isSuccess {
                    print("登录成功")
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(updateRootVCNotification, object: self)
                    })
                } else {
                
                    SVProgressHUD.showErrorWithStatus("登录失败")
                }
            })
        }else {
        
            dismissViewControllerAnimated(true, completion: nil)
        }
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
    
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
    
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
    
        SVProgressHUD.dismiss()
    }
}
